package com.heima.comment.service.impl;

import com.heima.apis.wemedia.IWemediaClient;
import com.heima.comment.dao.CommentRepository;
import com.heima.comment.dao.LikeRepository;
import com.heima.comment.service.ICommentRepayService;
import com.heima.comment.util.ApTokenThreadLocalUtil;
import com.heima.common.exception.CustomException;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.Comment;
import com.heima.model.comment.pojos.Like;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class CommentRepayServiceImpl implements ICommentRepayService {

    @Resource
    private CommentRepository commentRepository;

    @Resource
    private LikeRepository likeRepository;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private IWemediaClient wemediaClient;

    /**
     * 评论回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        ApUser user = ApTokenThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        String commentId = dto.getCommentId();
        String content = dto.getContent();

        try {
            wemediaClient.commentInspect(content);
        } catch (Exception e) {
            throw new CustomException(AppHttpCodeEnum.RUBBISH_COMMENT);
        }

        Comment comment = commentRepository.findById(commentId).get();
        if (comment == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //保存回复评论信息
        Comment repayComment = new Comment();
        repayComment.setContent(content);//回复评论内容
        repayComment.setLikeNum(0);//回复的点赞数
        repayComment.setUserId(user.getId());//回复用户Id
        repayComment.setAuthorId(comment.getUserId());//被回复用户Id
        repayComment.setReplyNum(0);//回复数
        repayComment.setPublishTime(new Date());//回复日期
        repayComment.setParentId(commentId);//被回复评论ID
        repayComment.setArticleId(comment.getArticleId());//被回复的评论作者
        commentRepository.save(repayComment);

        //评论回复数加一
        comment.setReplyNum(comment.getReplyNum() + 1);
        commentRepository.save(comment);

        return ResponseResult.okResult(null);
    }

    /**
     * 加载回复评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        ApUser user = ApTokenThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        String commentId = dto.getCommentId();
        Date minDate = dto.getMinDate();
        int size = dto.getSize();

        Query query = Query.query(Criteria.where("publishTime").lt(minDate).and("parentId").is(commentId))
                .with(Sort.by(Sort.Direction.DESC, "publishTime"))
                .with(PageRequest.of(0, 10));
        List<Comment> commentRepays = mongoTemplate.find(query, Comment.class);
        System.out.println(commentRepays);

//        Pageable pageable = PageRequest.of(0, size);
//        List<Comment> commentRepays = commentRepository.findAllByPublishTimeBeforeAndParentIdOrderByPublishTimePublishTimeDesc(minDate, commentId, pageable);

        List<Map<String, Object>> vos = new ArrayList();
        for (Comment repayComment : commentRepays) {
            Map<String, Object> vo = new HashMap<>();
            vo.put("content", repayComment.getContent());
            vo.put("userId", repayComment.getUserId());
            vo.put("likes", repayComment.getLikeNum());
            vo.put("createdTime", repayComment.getPublishTime());
            Like like = likeRepository.findByUserIdAndCommentId(user.getId(), repayComment.getId());
            if (like != null) {
                vo.put("operation", 0);
            }
            vos.add(vo);
        }

        return ResponseResult.okResult(vos);
    }

    /**
     * 评论回复点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeCommentRepay(CommentRepayLikeDto dto) {
        ApUser user = ApTokenThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        String commentRepayId = dto.getCommentRepayId();
        System.out.println("commentRepayId = " + commentRepayId);
        short operation = dto.getOperation();

        //判断是否点赞
        Like like = likeRepository.findByUserIdAndCommentId(user.getId(), commentRepayId);

        //如果是点赞操作且已经点赞
        if (operation == 0 && like != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已点赞");
        }

        //获取评论以修改评论信息
        Comment comment = commentRepository.findById(commentRepayId).get();
        if (comment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        if (operation == 0) {
            //点赞
            like = new Like();
            like.setCommentId(commentRepayId);
            like.setUserId(user.getId());
            likeRepository.save(like);

            //点赞数更新
            comment.setLikeNum(comment.getLikeNum() + 1);
        } else {
            //取消点赞
            likeRepository.delete(like);

            //点赞数更新
            comment.setLikeNum(comment.getLikeNum() - 1);
        }
        commentRepository.save(comment);

        Map<String, Object> vo = new HashMap<>();
        vo.put("likes", comment.getLikeNum());
        return ResponseResult.okResult(vo);
    }
}
